/*
                    Label Class Implementation
*/
#include "Label.h"

Label::Label()
{
    TTFfont = NULL;
    Image = NULL;

    Position = Point(0,0);

    ForeColour.r = 0;
    ForeColour.g = 0;
    ForeColour.b = 0;

    bVisible = true;
    bEnabled = true;

    bOutlined = false;
}

Label::~Label()
{
    if (TTFfont != NULL)
    {
        TTF_CloseFont(TTFfont);
        TTFfont = NULL;
    }

    if (Image != NULL) { SDL_FreeSurface(Image); Image = NULL; }
}

int Label::Initialise(Point NewPosition, string strFilepath, int iNewSize, string strNewText, SDL_Color NewColor, bool bNewOutlined)
{
    iSize = iNewSize;

    Position = NewPosition;

    ForeColour = NewColor;

    bOutlined = bNewOutlined;

    TTFfont = TTF_OpenFont(strFilepath.c_str(), iSize);

    if (TTFfont == NULL)
    {
        printf("Font Init Error: %s\n", TTF_GetError());
        return -1;
    }

    strText = strNewText;

    UpdateText();
}

int Label::UpdateText()
{
    SDL_FreeSurface(Image);
    Image = OptimiseAlphaSurface(TTF_RenderText_Blended(TTFfont, strText.c_str(), ForeColour));

    if (bOutlined == true)
    {
        OutlineText(Image, GetSDLColor(0, 0, 0), ForeColour);
    }

    if (Image == NULL)
    {
        #ifdef DEBUG
            printf("Label Error: %s\n", TTF_GetError());
        #endif

        return -1;
    }
}

void Label::setSize(int iNewSize)
{
    iSize = iNewSize;
}

int Label::getSize()
{
    return iSize;
}

void Label::setPosition(Point NewPosition)
{
     Position = NewPosition;
}

Point Label::getPosition()
{
       return Position;
}

void Label::setText(string strNewText)
{
     strText = strNewText;

     UpdateText();
}

string Label::getText()
{
       return strText;
}

int Label::getWidth()
{
    if (Image == NULL)
    {
        return 0;
    }

    return Image->w;
}

int Label::getHeight()
{
    if (Image == NULL)
    {
        return 0;
    }

    return Image->h;
}

void Label::setForeColour(int nr, int ng, int nb)
{
     ForeColour.r = nr;
     ForeColour.g = ng;
     ForeColour.b = nb;

     UpdateText();
}

int Label::BlitToSurface(SDL_Surface *screen)
{
    if (bVisible == true)
    {
        SDL_Rect dest;
        dest.x = static_cast<int>(Position.x);
        dest.y = static_cast<int>(Position.y);
        SDL_BlitSurface(Image, NULL, screen, &dest);
    }
}

int Label::BlitToFrame(SDL_Surface *surface, Point FramePosition)
{
    if (bVisible == true)
    {
        SDL_Rect dest;
        dest.x = static_cast<int>(Position.x) + static_cast<int>(FramePosition.x);
        dest.y = static_cast<int>(Position.y) + static_cast<int>(FramePosition.y);
        SDL_BlitSurface(Image, NULL, surface, &dest);
    }
}
